package com.example.demo.smartLamp.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.common.exception.CustomException;
import com.example.demo.common.util.JwtUitls;
import com.example.demo.smartLamp.entity.User;
import com.example.demo.smartLamp.entity.request.UserInfoGetRequest;
import com.example.demo.smartLamp.entity.request.UserLoginRequest;
import com.example.demo.smartLamp.entity.response.UserInfoGetResponse;
import com.example.demo.smartLamp.entity.response.UserLoginResponse;
import com.example.demo.smartLamp.mapper.UserMapper;
import com.example.demo.smartLamp.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 祁荣博 胡绍宇
 * @since 2022-07-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    UserMapper userMapper;

    @Override
    public UserInfoGetResponse userInfoGet(UserInfoGetRequest userInfoGetRequest) {
        User user = new User();
        user = userMapper.selectOne(
                Wrappers.lambdaQuery(User.class)
                        .eq(User::getUserId,userInfoGetRequest.getUserId())
        );

        UserInfoGetResponse userInfoGetResponse = new UserInfoGetResponse();
        userInfoGetResponse.setUserId(user.getUserId());
        userInfoGetResponse.setUserDevice(user.getUserDevice());
        userInfoGetResponse.setUserEmail(user.getUserEmail());
        userInfoGetResponse.setUserAccount(user.getUserAccount());
        userInfoGetResponse.setUserName(user.getUserName());
        userInfoGetResponse.setUserPower(user.getUserPower());

        return userInfoGetResponse;
    }

    @Override
    public User selectUserById(String id) {
        User user = new User();
        user = userMapper.selectOne(
                Wrappers.lambdaQuery(User.class)
                        .eq(User::getUserId,id)
        );

        return user;
    }

    @Override
    public UserLoginResponse userLogin(UserLoginRequest userLoginRequest) {

        User user = new User();
//        user = userMapper.selectOne(
//                Wrappers.lambdaQuery(User.class)
//                        .eq(User::getUserAccount, userLoginRequest.getUserAccount())
//                        .eq(User::getUserPassword, userLoginRequest.getUserPassword())
//        );
        user = userMapper.selectUser(userLoginRequest.getUserAccount());
        if(user == null) {
            throw new CustomException("请正确输入帐号或密码");
        }
        if(!user.getUserPassword().equals(userLoginRequest.getUserPassword())){
            throw new CustomException("密码错误");
        }

        UserLoginResponse userLoginResponse = new UserLoginResponse();
        userLoginResponse.setToken(JwtUitls.createToken(user.getUserId(),user.getUserPassword()));

        return userLoginResponse;
    }
}
